package cn.bluedot.tea.filter;

import java.io.IOException;
import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Set;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.annotation.WebInitParam;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import cn.bluedot.tea.pojo.domain.User;
import cn.bluedot.tea.service.UserService;


public class MenuFilter implements Filter {
	
	private static Set<String> set;
	
	public void init(FilterConfig config) throws ServletException {
		String ignore = config.getInitParameter("ignore");
		String[] ignores = ignore.split(";");
		
		this.set = new HashSet<String>(Arrays.asList(ignores)); 
	}
	
	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
		
		HttpServletRequest req = (HttpServletRequest) request;
		HttpServletResponse res = (HttpServletResponse) response;
		
		String context = req.getContextPath().trim();
		String requestUri = req.getRequestURI().trim();
		
		String path = requestUri.replace(context, "").replaceFirst("/", "");
		
		if(path.equals("") || path == null || set.contains(path) || path.contains("static") || path.contains("assets")) { //放行忽略项
			chain.doFilter(request, response);
			return;
		}
		
		User user = (User) req.getSession().getAttribute("user");
		
		if(user == null) {
			res.sendRedirect(req.getContextPath());
			return;
		}else {
			path = ("/"+path).replace(".do", "");
			//判断权限
			try {
				Set<?> menu = UserService.getMenuSet(user.getRoleId());
				if(menu == null) {//数据库没有权限，直接打回登录
					res.sendRedirect(req.getContextPath());
					return;
				}
				
				//登录成功后首页放行 /index.jsp
				if(menu.contains(path) || path.equals("/index.jsp") || path.contains(".jsp")) {
					chain.doFilter(request, response);
				}else {
					HashMap<String, Object> error = new HashMap<String, Object>();
					error.put("title", "您无权限访问，请联系管理员！");
					error.put("message", "检测到您暂时没有足够的权限访问当前页，如果需要当前功能权限请联系管理员。");
					req.setAttribute("error", error);
					req.getRequestDispatcher("/error.jsp").forward(req, res);
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}
}
